package pl.un4giv3n.mightvsmagic.action.clan;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import pl.un4giv3n.mightvsmagic.utils.ClanUtil;

public class LeaveClanAction extends ClanAction{

	private static final long serialVersionUID = 1L;

	@Override
	public String execute() {
		EntityManager entityManager = getEntityManager();
		user = getSessionUser(entityManager);
		if (user == null) {
			addActionError("Zaloguj się");
			entityManager.close();
			return LOGIN;
		}
		EntityTransaction transaction = entityManager.getTransaction();
		transaction.begin();
		clan = user.getClan();
		clan.getUsers().remove(user);
		entityManager.merge(user);
		if(clan.getUsers().isEmpty()){
			ClanUtil.endClanWars(clan.getId(), entityManager);
			entityManager.remove(clan);
		}else{
			entityManager.merge(clan);
		}
		user.setClan(null);
		user.setClanAdmin(false);
		user.setClanMod(false);
		user.setClanRank("");
		entityManager.flush();
		transaction.commit();
		entityManager.close();
		return SUCCESS;
	}

}
